package com.jzwl.common.upload.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.jzwl.common.constant.Constants;
import com.jzwl.common.id.Sequence;
import com.jzwl.common.upload.FileUploadUtils;
import com.jzwl.common.upload.MultipartUploadSample;

@Service("uploadImgService")
public class UploadImgService {
	@Autowired
	private Constants constants;
	/**
	 * 
	 * 项目名称：dlws-xiaoka-bbs
	 * 描述：上传图片统一调用（上传静态资源，上传oss）
	 * 创建人： ln
	 * 创建时间： 2016年9月6日
	 * 标记：工具
	 * @return
	 * @version
	 */
	public String uploadImg(int type, MultipartFile img,String flag){
		//1:type表示上传到某一个资源上去1：表示静态资源，2：表示上传到oss服务器上去
		//2:img 要上传的图片
		//3:flag 当type 为2时 flag表示是那个项目的图片eg：bbs，tg,zb..当为1时可传null,
		if(type==1){
				try {
					String filename = URLEncoder.encode(img.getOriginalFilename(),"utf-8");
					long datelong = System.currentTimeMillis();
					String imgPath = constants.getXiaoka_weixin_targetdirectory_goods_detail()+datelong+"_"+filename;
					String targetPath = constants.getXiaoka_weixin_staticresource_path()+imgPath;
					FileUploadUtils.uploadToStaticResourceServerByJersey(img,targetPath);				
					return targetPath;	
				} catch (Exception e) {
					e.printStackTrace();
				}
		}else if(type==2){
			java.util.Random random=new java.util.Random();// 定义随机类
			int keynum = random.nextInt(1000);
			String sdf = Sequence.nextId();
			String key = "bbs/"+sdf+String.valueOf(keynum);
			String beforUrl = constants.getXiaoka_bbs_oosGetImg_beforeUrl();//上传oss中地址前半段
			try {
				boolean b = MultipartUploadSample.uploadOssImg(key,img);
				if(b){
					return beforUrl+key;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
}
